package com.exercise;

import com.example.util.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class Exercise1 {

    @Test
    public void testInsert() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("名称:");
        String name = scanner.next();
        System.out.print("邮箱:");
        String email = scanner.next();
        System.out.print("生日:");
        String birth = scanner.next();

        String sql = "INSERT INTO `customers`(`name`, `email`, `birth`) VALUES (?, ?, ?)";
        boolean result = update(sql, name, email, birth);
        if (result) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
    }

    // 通用的增删改操作
    public static boolean update(String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            // 获取连接
            connection = JDBCUtils.getConnection();
            // 编译SQL
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            // 执行操作
            // preparedStatement.execute();
            return preparedStatement.executeUpdate() > 0;
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 释放资源
            JDBCUtils.closeResource(connection, preparedStatement);
        }
        return false;
    }

}
